<template>
  <div class="menu-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button
            v-permission="'menus.create'"
            type="primary"
            @click="handleAdd"
          >
            新增菜单
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="菜单名称">
          <el-input v-model="searchForm.title" placeholder="请输入菜单名称" clearable />
        </el-form-item>
        <el-form-item label="菜单类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="目录" :value="1" />
            <el-option label="菜单" :value="2" />
            <el-option label="按钮" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        row-key="id"
        :tree-props="{ children: 'children' }"
        default-expand-all
      >
        <el-table-column prop="title" label="菜单名称" width="200" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 1 ? 'info' : row.type === 2 ? 'success' : 'warning'">
              {{ row.type === 1 ? '目录' : row.type === 2 ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由地址" />
        <el-table-column prop="component" label="组件路径" />
        <el-table-column prop="icon" label="图标" width="100" />
        <el-table-column prop="permission" label="权限标识" />
        <el-table-column prop="sort" label="排序" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              v-permission="'menus.update'"
              type="primary"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-permission="'menus.delete'"
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <MenuDialog
      v-model="dialogVisible"
      :menu-id="currentMenuId"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { useMenuStore } from '@/stores/menu'
import MenuDialog from './components/MenuDialog.vue'

const loading = ref(false)
const dialogVisible = ref(false)
const currentMenuId = ref(null)
const router = useRouter()
const menuStore = useMenuStore()

const searchForm = reactive({
  title: '',
  type: '',
  status: '',
})

const tableData = ref([])

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = { ...searchForm }
    // 如果没有搜索条件，请求树形数据
    if (!searchForm.title && !searchForm.type && !searchForm.status) {
      params.tree = true
    }
    const res = await request.get('/menus', { params })
    if (res.code === 200) {
      // 如果有搜索条件，返回平铺数据；否则返回树形数据
      if (searchForm.title || searchForm.type || searchForm.status) {
        // 将平铺数据构建为树形结构显示
        tableData.value = buildTree(res.data, 0)
      } else {
        // 后端已返回树形数据
        tableData.value = res.data
      }
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 构建树形结构
const buildTree = (list, parentId) => {
  const tree = []
  list.forEach(item => {
    if (item.parent_id === parentId) {
      const children = buildTree(list, item.id)
      if (children.length > 0) {
        item.children = children
      }
      tree.push(item)
    }
  })
  return tree
}

// 搜索
const handleSearch = () => {
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    type: '',
    status: '',
  })
  loadData()
}

// 新增
const handleAdd = () => {
  currentMenuId.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  currentMenuId.value = row.id
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该菜单吗？', '提示', {
      type: 'warning',
    })
    const res = await request.delete(`/menus/${row.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 成功回调
const handleSuccess = async () => {
  // 重新加载菜单列表数据
  loadData()
  
  // 刷新菜单路由（重新获取菜单并更新路由）
  try {
    ElMessage.info('正在更新菜单路由...')
    const success = await menuStore.refreshRoutes(router)
    if (success) {
      ElMessage.success('菜单路由已更新，页面即将刷新')
      // 保存当前路径（如果当前路径是菜单管理页面，刷新后回到菜单管理页面）
      const currentPath = router.currentRoute.value.path
      // 等待一下让路由更新完成
      await new Promise(resolve => setTimeout(resolve, 500))
      // 刷新当前页面以应用路由更改
      // 刷新后，路由守卫会重新加载菜单，菜单数据会是最新的
      window.location.href = currentPath
    } else {
      ElMessage.warning('菜单路由更新失败，请手动刷新页面')
    }
  } catch (error) {
    console.error('刷新菜单路由失败:', error)
    ElMessage.warning('菜单路由刷新失败，请手动刷新页面')
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.menu-container {
  // padding 由 app-container 统一管理
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}
</style>
